<template>
    <div class="allCustomersManagement">
      <div class="allCustomersManagement_buttons">
          <Button type="primary" style="marginRight:8px" @click="addPeople">新建员工</Button>
          <Button type="warning" @click="changeDepartmentBegin">变更部门</Button>
      </div>
      <Table ref="TableHeight" class="table" @on-select="selectListed" :max-height="onresizeHeight" :columns="columns1" :data="memberList"></Table>
      <!-- 分页 -->
      <div class="pagePublicStyle" v-show="pageData.total > 0">
         <div class="totalCount">
             当前第 {{pageData.page}} 页， 
             当前第 {{(pageData.page-1)*pageData.rows+1}} 条到第 {{pageData.page*pageData.rows>pageData.total?pageData.total:pageData.page*pageData.rows}} 条，
             共 {{pageData.total}} 条
         </div>
        <Page :current="pageData.page" :total="pageData.total" :page-size-opts="pageData.pageSizeOpts" @on-change="pageOnChangeFun" @on-page-size-change="pageOnPageSizeChangeFun" show-elevator show-sizer />
      </div>
      <!-- table 头部筛选 -->
      <table_filter :options="options" @cancelFilterFun="cancelFilterFun" @okFilterFun="okFilterFun"></table_filter>
      <!-- 新建员工 -->
     <Modal v-model="addEmployee" width="500" :title="moudleTitle">
        <Form ref="addEmployee" :model="addEmployeeMess" :rules="addEmployeeMessRule" :label-width="80">
            <FormItem label="姓名" prop="userName">
              <Input v-model="addEmployeeMess.userName" placeholder="请填写姓名"></Input>
           </FormItem>
           <FormItem label="手机" prop="phone">
              <Input v-model="addEmployeeMess.phone" placeholder="请填写手机号"></Input>
           </FormItem>
           <FormItem label="角色" prop="roleIds">
            <Select v-model="addEmployeeMess.roleIds" multiple placeholder="请选择角色">
                 <Option v-for="item in roleList" :key="item.roleId" :value="item.roleId">{{item.roleName}}</option>
            </Select>
           </FormItem>
           <FormItem label="部门" prop="orgId">
             <Cascader  v-model="departments" v-if="moudleTitle == '新建员工'" :data="selectMemberList"   change-on-select trigger="hover" filterable :render-format="format"></Cascader>
             <Input v-else type="text" v-model="addEmployeeMess.orgName" disabled></Input>
           </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="addEmployee = false">取消</Button>
          <Button type="primary" @click="newEmployee('addEmployee')">确定</Button>
        </div>
     </Modal>
     <!-- 变更部门 -->
     <Modal v-model="changeDepartment" width="500" title="变更部门">
        <Form ref="changeDepartment" :model="departmentList"  :rule="departmentRule" :label-width="80">
           <FormItem label="部门" prop="departmentname">
            <Cascader v-model="departments" :data="selectMemberList"   change-on-select trigger="hover" filterable :render-format="formatChange"></Cascader>
           </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="changeDepartment = false">取消</Button>
          <Button type="primary" @click="changeDepartmentSure('changeDepartment')">确定</Button>
        </div>
     </Modal>
       <!-- 编辑个人资料 -->
     <Modal v-model="editEmployee" width="500" title="编辑">
        <Form ref="editEmployee" :model="editEmployeeMess" :rules="editEmployeeRule" :label-width="80">
            <FormItem label="姓名" prop="name">
              <Input v-model="editEmployeeMess.name" placeholder="请填写姓名"></Input>
           </FormItem>
           <FormItem label="手机号" prop="phone">
              <Input v-model="editEmployeeMess.phone" placeholder="请填写手机号"></Input>
           </FormItem>
           <FormItem label="角色" prop="role">
            <Select v-model="editEmployeeMess.role"  placeholder="请选择角色">
                <Option value="beijing">New York</Option>
                <Option value="shanghai">London</Option>
                <Option value="shenzhen">Sydney</Option>
            </Select>
           </FormItem>
           <FormItem label="部门" prop="department">
            <Select v-model="editEmployeeMess.department" multiple placeholder="请选择部门">
                <Option value="beijing">New York</Option>
                <Option value="shanghai">London</Option>
                <Option value="shenzhen">Sydney</Option>
            </Select>
           </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="editEmployee = false">取消</Button>
          <Button type="primary" @click="editEmployeeSure('editEmployee')">确定</Button>
        </div>
     </Modal>
     <!-- 删除员工 -->
     <Modal v-model="deleEmployee" width="500" title="删除员工">
         <Form ref="deleEmployee" :model="deleEmployeeMess" :rules="deleEmployeeRule">
           <FormItem label="被删除的员工所跟进的客户分配给：" prop="name">
            <!-- <Select v-model="deleEmployeeMess.name" placeholder="请选择员工">
                <OptionGroup :label="item.title" v-for="item in selectMemberList"  :key="item.title">
                  <Option v-for="it in item.children" :value="it.value" :key="it.value">{{it.title}}</Option>
                </OptionGroup>
            </Select> -->
           </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="deleEmployee = false">取消</Button>
          <Button type="primary" @click="deleEmployeeSure('deleEmployee')">确定</Button>
        </div>
     </Modal>
    </div>
    
</template>
<script>
  import table_filter from '@/components/table_filter'
  import {getpeopleList, getPeopleAdd, getPeopleDelete, getRoleList, 
  getDepartmentChange, getUserDisabled
  } from "@/api/system_center"
  export default {
    components: {
      table_filter
    },
    props:{
      treeList:{
        type:Array,
        default:()=>[]
      }
    },
    data() {
     const validateArray = (rule, value, callback) =>{
       if(!value || value.length<1)callback(new Error("请选择角色"))
       else callback()
     }
     const validatePhone = (rule, value, callback) =>{
       if(!value || !(/^1[3456789]\d{9}$/.test(value)))callback(new Error("请输入正确的手机号"))
       else callback()
     }
     return {
          onresizeHeight: 0,
          pageData: {
            total: 0,
            page: 1,
            rows: 10,
            pageSizeOpts: [10,20, 30, 40, 50]
          },
          moudleTitle:'新建员工',
          options: { 
            type: '',   // form类型  Input / DatePicker / Checkbox / Select / 操作配置头部
            placeholder: '',  // 提示语
            left: -1000,    // 弹框fixed => left
            iconLeft: 0,  // 弹框icon => left
            top: -1000,    // 弹框fixed => top
            width: 218,   // 弹框fixed => top
            setTimeout: null,    // 鼠标离开三角形 200毫秒 关闭弹框
            customerName: '',  // 客户姓名 字段
            phoneNumber: '', // 电话 字段
            areaVal: [],  // 地区 字段
            //areaList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 地区 字段
            //sourceVal: [],  // 来源 字段
            //sourceList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 来源 数据
           // customerLevelVal: [], // 客户等级 字段
           // customerLevelList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 客户等级 数据
           // creationTimeVal: '',  // 创建时间 字段
           // autoCompleteVal: '', // 服务人员 字段
           // daterange: '',   // 年月日
           // datetimerange: '',  // 年月日时分秒
           // multipleCheckbox: [],  // Checkbox 字段
           // checkboxList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}], // Checkbox数据
           // selectVal: [],  // Select 多项 字段
           // selectList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}], // select数据
           // operatingVal: [],   // 操作 字段
            tableTitleList: []     // 操作 数据
            // tableTitleList: [{name: '订单编号', val: '11', selected: false}]     // 操作 数据
          },
          columns1: [
            {
                type: 'selection',
                width: 60,
                align: 'center'
            },
            {
              title: '姓名',
              key: 'userName',
              minWidth: 100,
              render: (h, params) => {
                return h("div", [
                  h(
                    "span",
                    {
                      style: {
                        display: "inline-block",
                        width: "100%",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap"
                      },
                      domProps: {
                        title: params.row.name1
                      }
                    },
                    params.row.userName
                  )
                ]);
              },
              renderHeader: (h, params) => {
                return h('div',[
                  h('span', {}, '姓名'),
                  h('Icon', {
                    props: {
                      type: 'ios-arrow-down',
                      size: '16'
                    },
                    style: {
                      marginLeft: '5px'
                    },
                    nativeOn: {
                      'mouseover': (event) => {
                        event.stopPropagation();
                        this.thMouseoverFun(event, 'input-customerName', '请输入姓名', 218);
                      },
                      'mouseleave': (event) => {
                        event.stopPropagation();
                        this.thMouseoutFun();
                      }
                    }
                  })
                ])
              }
            },
            {
              title: '手机号',
              key: 'phone',
              minWidth: 130,
              // render: (h, params) => {
              //   return h('div',  this.$options.filters.mobilePhoneNumberFourAsterisk(params.row.phone) || '-');
              // },
              renderHeader: (h, params) => {
                return h('div',[
                  h('span', {}, '手机号'),
                  h('Icon', {
                    props: {
                      type: 'ios-arrow-down',
                      size: '16'
                    },
                    style: {
                      marginLeft: '5px'
                    },
                    nativeOn: {
                      'mouseover': (event) => {
                        event.stopPropagation();
                        this.thMouseoverFun(event, 'input-phoneNumber', '请输入电话', 218);
                      },
                      'mouseleave': (event) => {
                        event.stopPropagation();
                        this.thMouseoutFun();
                      }
                    }
                  })
                ])
              }
            },
            {
              title: '角色',
              key: 'roles',
              minWidth: 180,
              render: (h, params) => {
                return h('div',  this.changeRole(params.row.roles,'roleName'));
              },
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '角色'),
              //     h('Icon', {
              //       props: {
              //         type: 'ios-arrow-down',
              //         size: '16'
              //       },
              //       style: {
              //         marginLeft: '5px'
              //       },
              //       nativeOn: {
              //         'mouseover': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoverFun(event, 'Select-areaVal-areaList', '请选择地区', 200);
              //         },
              //         'mouseleave': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoutFun();
              //         }
              //       }
              //     })
              //   ])
              // }
            },
            {
              title: '部门',
              key: 'orgName',
              minWidth: 120,
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '部门'),
              //   ])
              // }
            },
            {
              title: '关联案场',
              key: 'buildingVOS',
              minWidth: 120,
               render: (h, params) => {
                return h('div',  this.changeRole(params.row.buildingVOS,'buildingName'));
              },
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '关联案场'),
              //   ])
              // }
            },
            {
              title: '操作',
              fixed: 'right',
              width: 140,
              align: 'center',
              render: (h, params) => {
                return h('div', [
                  h('a', {
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                        this.viewClick(params.row);
                      }
                    }
                  }, '编辑'),
                  //  h('a', {
                  //   style:{
                  //      color:'red',
                  //      padding:'0 6px'
                  //   },
                  //   on: {
                  //     click: (e) => {
                  //       e.stopPropagation();
                  //       this.deleEmployee = true;

                  //     }
                  //   }
                  // }, '删除'),
                   h('a', {
                    style:{
                       color:'red',
                       padding:'0 6px'
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                        this.openAuthority(params.row)
                        // this.deleEmployee = true;
                      }
                    }
                  }, params.row.validate == 2?'开启':'禁用'),

                ]);
              },
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '操作'),
              //     h('Icon', {
              //       props: {
              //         type: 'md-settings',
              //         size: '16'
              //       },
              //       style: {
              //         marginLeft: '5px'
              //       },
              //       nativeOn: {
              //         'mouseover': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoverFun(event, 'tableTitle-operatingVal-tableTitleList', '', 300);
              //         },
              //         'mouseleave': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoutFun();
              //         }
              //       }
              //     })
              //   ])
              // }
            }
          ],
          memberList: [],
          addEmployeeMessRule:{
            userName: [
              { required: true, message: '请填写名字', trigger: 'blur' }
            ], 
             phone: [
              { validator: validatePhone,  trigger: 'blur' }
            ], 
             orgId: [
              { required: true, message: '请选择角色', trigger: 'change' }
            ], 
             roleIds: [
              { validator: validateArray,  trigger: 'blur'}
            ], 
          },
          editEmployeeRule:{
            name: [
              { required: true, message: '请填写名字', trigger: 'blur' }
            ], 
             phone: [
              { required: true, message: '请填写手机号', trigger: 'blur' }
            ], 
             role: [
              { required: true, message: '请选择角色', trigger: 'change' }
            ], 
             department: [
              { validator: validateArray,  trigger: 'blur'}
            ], 
          },
          addEmployee:false,
          addEmployeeMess:{
              roleIds:[],
              orgIds:[]
          },
          selectionList:[],
          departmentList:{
              departmentname:[]
          },
          changeDepartment:false,
          departmentRule:{
            departmentname: [{required: true, message: '请选择部门', trigger: 'blur' }], 
          },
          editEmployeeMess:{},
          editEmployee:false,
          selectMemberList:[],
          deleEmployee:false,
          deleEmployeeRule:{
             name:[{ required: true, message: '请选择角色', trigger: 'change' }]
          },
          deleEmployeeMess:{},
          roleList:[],
          departments:[]
   }
  },
  created() {
      // 初始化获取数据
      // console.log('测试111111')
      this.initData()
    },
    activated() {

    },
    deactivated() {

    },
    mounted() {
       this.changeTreeFormation(this.treeList)
    },
    watch: {
      treeList(newValue){
        this.changeTreeFormation(newValue)
      }
    },
    methods: {
      //新建员工
      addPeople(){
       this.getRoles()
       this.moudleTitle = "新建员工";
       this.addEmployeeMess= {
          roleIds:[],
          orgIds:[]
       },
       this.departments = [];
       this.addEmployee = true;
      },
     //点击新建确认员工按钮
     newEmployee(name){
       this.$refs[name].validate((valid) => {
           if (valid) {
               console.log("成功",this.addEmployeeMess);
               if(this.addEmployeeMess.userId){//编辑信息
                   this.editEmployeeSure(this.addEmployeeMess);
                   return;
               }
               //调取新建员工接口  如果当前显示的不是这么部门
               getPeopleAdd(this.addEmployeeMess).then(res=>{
                 this.$Message.success("员工添加成功")
                 this.$refs[name].resetFields();
                 this.getmemberList();
                 this.$emit("getDepartmentList")
                 this.addEmployee = false;
               }).catch(err=>this.$Message.error(err))
           } 
        })
     }, 
     //将部门树结构改成需要的结构
     changeTreeFormation(mess){
        let newMess = JSON.parse(JSON.stringify(mess));
        this.recursionTree(newMess);
        this.selectMemberList = newMess;
     },
     //递归方法
     recursionTree(item){
      item.map(item=>{
         item.value = item.orgId;
         item.label = item.title;
         item.children && this.recursionTree(item.children)
      })
     },
     //将角色数组转变成字符串
     changeRole(mess,name){
       if(!mess || !Array.isArray(mess) || mess.length<1)return '';
        let str =[];
       mess.map(item=>item && str.push(item[name]));
       str = [...new Set(str)]
       return str.join(",")
     },
     //部门列表选择
      format (labels, selectedData){
        selectedData.length>0 && (this.addEmployeeMess.orgId = selectedData[selectedData.length-1].value);
        return labels[labels.length-1]
      },
      //获取角色权限
      getRoles(){
        if(this.roleList.length>0)return;
        getRoleList().then(res=>{
          console.log("获取员工列表",res)
           this.roleList = res.list != null?res.list:[];
        }).catch(err=>this.$Message.error(err))
      },
      formatChange(labels, selectedData){
        selectedData.length>0 && (this.departmentList.departmentname = selectedData[selectedData.length-1].value);
        return labels[labels.length-1]
      },
      // table 鼠标移到三角形事件
      thMouseoverFun(event, type, placeholder, width) {
        this.options.type = type
        this.options.placeholder = placeholder
        this.options.left = event.currentTarget.getBoundingClientRect().left - (width/2 - 5) <= 200 ? 200 : (event.currentTarget.getBoundingClientRect().left - (width/2 - 5) + width) > document.documentElement.clientWidth ? (document.documentElement.clientWidth - width) : event.currentTarget.getBoundingClientRect().left - (width/2 - 5)
        this.options.iconLeft = event.currentTarget.getBoundingClientRect().left
        this.options.top = event.currentTarget.getBoundingClientRect().top + 24
        this.options.width = width
      },
      // table 鼠标离开三角形事件
      thMouseoutFun() {
        this.options.setTimeout = setTimeout(() => {
          this.options.left = -1000 
          this.options.top = -1000
        },100)
      },
      // table from 取消事件
      cancelFilterFun(options) {
        console.log('cancelFilterFun', options)
      },
      // table from 确定事件
      okFilterFun(options) {
        let { customerName, phoneNumber} = options,params = {phone:phoneNumber,userName:customerName};
        this.getmemberList(params)
        
        console.log('okFilterFun', options)
      },
      // 分页 页码改变事件
      pageOnChangeFun(page) {
        console.log('分页 页码改变事件')
          this.pageData.page = page;
          this.getmemberList()
      },
      // 分页 每页条数改变事件
      pageOnPageSizeChangeFun(rows) {
        console.log('分页 每页条数改变事件')
        this.pageData.rows = rows;
         this.pageData.page = 1;
        this.getmemberList()
      },
      //获取员工列表
      getmemberList(params={}){
        let {page, rows } = this.pageData;
        params.orgId ?this.orgId =  params.orgId: params.orgId = this.orgId;
        params = Object.assign(params,{page, rows})
        getpeopleList(params).then(res=>{
            console.log("获取员工列表",res);
            this.memberList = res.list || [];
            this.pageData.total = res.total-0;
        })
      },
      // 初始化获取数据
      initData() {
        this.$nextTick(() => {
          this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
        });
        window.onresize = () => {
         return (() => {
           setTimeout(() => {
             this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150
           }, 10);
          })();
        };
      },
      // 打开编辑
      viewClick(val) {
         let arr = JSON.parse(JSON.stringify(val));
         console.log(arr);
         this.getRoles()
         this.moudleTitle = "编辑员工资料";
         let newArray = [];
         if(arr.roles && arr.roles.length>0)arr.roles.map(item=>newArray.push(item.roleId));
         arr.roleIds = newArray;
         arr.orgIds = [arr.orgName]
         this.addEmployeeMess=arr;
         this.addEmployee = true;
         console.log(this.addEmployeeMess)
      },
      //编辑员工信息
      editEmployeeSure(mess){
          getDepartmentChange(mess).then(res=>{
             this.$Message.success("修改成功")
             this.addEmployee = false;
             this.getmemberList()
          }).catch(err=>this.$Message.error(err))
      },
      //列表选中
      selectListed(selection,row){
          console.log(selection,row)
         this.selectionList = selection;
      },
      //变更部门
      changeDepartmentBegin(){
         if(this.selectionList.length <1)return this.$Message.error("请选择员工")
         else if(this.selectionList.length >1)return this.$Message.error("只能选择一个员工");
         this.departments = [];
         this.changeDepartment = true;

      },
      //点击变更部门确定按钮
      changeDepartmentSure(name){
         if(!this.departmentList.departmentname)return this.$Message.error("请选择部门");
         let {userId} = this.selectionList[0];
          let params = {
            userId,
            orgId:this.departmentList.departmentname
          }
          getDepartmentChange(params).then(res=>{
              this.$Message.success("部门修改成功");
              this.departmentList.departmentname = '';
              this.changeDepartment = false;
              this.getmemberList()
          })
          
               //调取变更部门接口
               //this.$refs[name].resetFields();
           
        
      },
      //删除人员确定按钮
      deleEmployeeSure(name){
         this.$refs[name].validate((valid) => {
           if (valid) {
               console.log("成功")
               this.deleEmployee = false;
               //调取变更部门接口
               //this.$refs[name].resetFields();
           } 
        }) 
      },
      //开启权限
      openAuthority(mess){
          //调取权限接口
          let {userId, validate,userName} = mess;

        getUserDisabled({userId,validate:validate == '1'?'2':"1"}).then(res=>{
           this.$Message.success(`${userName}员工已被${validate == '1'?'禁用':'启用'}`);
           this.getmemberList();
        })
      }
    },
    
  }
</script>
<style lang="scss">
  .allCustomersManagement{
      height: calc(100% - 20px);
    .allCustomersP{
      padding: 8px 14px;
    }
    &_buttons{
      margin: 20px;
      text-align: right; 
    }
   /deep/.ivu-table-wrapper{
       height: 100%;
   }
   /deep/.ivu-table th{
       background-color: #f6f8fa;
   }
  }
  /* page */
  .pagePublicStyle{
    text-align: right;
    padding: 14px 0;
    margin-right: 30px;
  }
  .totalCount{
    float: left;
    line-height: 34px;
    padding-left: 20px;  
  }
 .table {
  .ivu-modal-header {
    border-bottom: 1px solid #e8eaec;
    padding: 14px 16px;
    line-height: 1;
  }
  .ivu-table-tbody .ivu-table-cell{
    overflow: inherit;
  }
  th .ivu-table-cell-with-selection{
    position: relative;
  }
  th .ivu-table-cell-with-selection::after{
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: #f8f8f9;
    z-index: 99;
  }
}

::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background-color: white;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}
::-webkit-scrollbar-thumb {
  background-color: #ccc;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}
</style>
